package com.zkld.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zkld.mapper.PluginMapper;
import com.zkld.pojo.Plugin;
import com.zkld.service.PluginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class PluginServiceImpl implements PluginService {

    @Autowired
    private PluginMapper pluginMapper;

    @Override
    public PageInfo<Plugin> queryByPageAndName(Integer p, String name, Integer pageSize) {
        PageHelper.startPage(p,pageSize);
        List<Plugin> lists = pluginMapper.queryByPageAndName(p,name);
        return new PageInfo<>(lists);
    }

    @Override
    public void add(Plugin plugin, MultipartFile signFile,MultipartFile pluginFile) {
        String signFilePath = fileUpload(signFile,"D:/pictures/").substring(12);
        plugin.setSign(signFilePath);

        String filePath = fileUpload(pluginFile,"D:/plugin/");
        plugin.setFilePath(filePath);

        pluginMapper.insert(plugin);
    }

    @Override
    public Plugin query(Plugin plugin) {
        return pluginMapper.query(plugin);
    }

    @Override
    public List<Plugin> queryAll() {
        return pluginMapper.queryAll();
    }

    @Override
    public void deleteById(Integer id) {
        pluginMapper.deleteByPrimaryKey(id);
    }

    @Override
    public PageInfo<Plugin> queryByPage(Integer p) {
        PageHelper.startPage(p,3);
        List<Plugin> lists = pluginMapper.queryAll();
        return new PageInfo<>(lists);
    }

    @Override
    public void update(Plugin plugin) {
        plugin.setSign(pluginMapper.query(plugin).getSign());
        plugin.setFilePath(pluginMapper.query(plugin).getFilePath());
        pluginMapper.updateByPrimaryKey(plugin);
        //System.out.println("更新----------");
    }

    private String fileUpload(MultipartFile multipartFile,String baseFilePath){
        String filePath = "";
        // 原始文件名
        String signFileName = multipartFile.getOriginalFilename();
        // 获取文件后缀(.jpg)
        String suffix = signFileName.substring(signFileName.lastIndexOf("."));
        // 生成文件存储的名称，UUID 避免冲突，并加上后缀
        String fileName = UUID.randomUUID().toString() + suffix;
        //存储路径
        filePath = baseFilePath + fileName;
        File saveFile = new File(filePath);
        try {
            multipartFile.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
}

